package com.eightbears.beboy.ui.user.activity;

import android.app.Activity;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.MainActivity;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.CommodityListAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.banner.LocalImageHolderView;
import com.eightbears.beboy.base.view.layout.MyGridLayoutManager;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.UserInfoEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.entity.status.Status_Products;
import com.eightbears.beboy.entity.status.Status_banners;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.w3c.dom.Text;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_BALANCE;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.PARAM_URL_PAGE;
import static com.eightbears.beboy.base.util.CommonAPI.PARAM_URL_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_BANNERS;
import static com.eightbears.beboy.base.util.CommonAPI.URL_PRODUCTS;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.ui.user.activity.SettingActivity.EVENT_USER_HEAD_UPDATE;
import static com.eightbears.beboy.ui.user.fragment.MyFragment.EVENT_UPDATE_USERINFO;

public class ShopActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener
        , OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {

    public static final String PARAMS_PRODUCTS_ITEM = "productsItem";

    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;
//    @BindView(R.id.iv_user_head)
//    ImageView iv_user_head;

    private ConvenientBanner mConvenientBanner;
    private ArrayList<String> bannerImages = new ArrayList<>();
    private LinearLayout ll_order;

    private CommodityListAdapter mCommodityListAdapter;
    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;
    private UserEntity mUserEntity;
    private MainActivity parentActivity;
    private UserInfoEntity mUserInfoEntity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop);
        ButterKnife.bind(this);
        initView();
        initData();
        initEvent();
    }


    @Override
    protected void initView() {
        mUserEntity = SPUtil.getUser();
        swipeLayout.setRefreshing(true);
        swipeLayout.setOnRefreshListener(this);
//        CommonUtils.loadImageView(getActivity(), mUserEntity.getData().getCover(), R.mipmap.default_head, iv_user_head);
        mUserInfoEntity = (UserInfoEntity) getExtras().get(EVENT_UPDATE_USERINFO);
        swipeLayout.setProgressViewOffset(true, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics()));
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new LinearLayoutManager(mContext));
        MyGridLayoutManager mWrapHeightGridLayoutManager = new MyGridLayoutManager(mContext, 2);
        rv_list.setLayoutManager(mWrapHeightGridLayoutManager);
        mCommodityListAdapter = new CommodityListAdapter();
        mCommodityListAdapter.setOnLoadMoreListener(this);
        mCommodityListAdapter.addHeaderView(addHeader());//添加头部布局
        mCommodityListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);//添加加载动画
        rv_list.setAdapter(mCommodityListAdapter);
    }

    @Override
    protected void initData() {
        getBanner();
        getShopList();

    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @Override
    protected void initEvent() {
        mCommodityListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                startLocalActivity((Activity) mContext, CommodityDetailActivity.class, PARAMS_PRODUCTS_ITEM, mCommodityListAdapter.getData().get(position));
            }
        });
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

//    //用户头像事件
//    @OnClick(R.id.iv_user_head)
//    void showLeft() {
//        parentActivity.showLeftMenu();
//    }

    /**
     * 添加recyclerView头部推荐布局
     *
     * @return
     */
    private View addHeader() {
        View view = getLayoutInflater().inflate(R.layout.head_shop_main, null);
        RecyclerView rv_classify = (RecyclerView) view.findViewById(R.id.rv_shop_classify);
        mConvenientBanner = (ConvenientBanner) view.findViewById(R.id.convenientBanner);
        TextView tv_balance = (TextView) view.findViewById(R.id.tv_balance);
        LinearLayout ll_balance = (LinearLayout) view.findViewById(R.id.ll_balance);
        LinearLayout ll_order1 = (LinearLayout) view.findViewById(R.id.ll_order);

        tv_balance.setText(mUserInfoEntity.getData().getBalance());
        ll_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity((Activity) mContext, MyWalletActivity.class, EVENT_UPDATE_USERINFO, mUserInfoEntity);
            }
        });


        ll_order1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity((Activity) mContext, UserTransactionActivity.class);
                // startLocalActivity(getActivity(), OrderListActivity.class);
            }
        });
        return view;
    }

    /**
     * 初始化头目条
     */
    private void initBanner() {

        mConvenientBanner.setPages(new CBViewHolderCreator<LocalImageHolderView>() {
            @Override
            public LocalImageHolderView createHolder() {
                return new LocalImageHolderView();
            }
        }, bannerImages)
                .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                .setOnItemClickListener(this);
        if (bannerImages.size() <= 1) {
            mConvenientBanner.setCanLoop(false);
        } else {
            mConvenientBanner.setCanLoop(true);
        }
    }


    /**
     * banner广告
     */
    private void getBanner() {
        bannerImages.clear();
        OkHttpUtils.get().url(URL_BANNERS)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("position", "2")
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                Status_banners status_banners = GsonUtil.fromJson(response, Status_banners.class);
                if (status_banners.getStatus_code() == Integer.parseInt(CONNECTION_STATUS_SUCCESS)) {
                    for (int i = 0; i < status_banners.getData().size(); i++) {
                        bannerImages.add(status_banners.getData().get(i).getCover());
                    }
                    initBanner();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }


    /**
     * 获取数据
     */
    public void getShopList() {
        OkHttpUtils.get().url(URL_PRODUCTS)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams(PARAM_URL_PAGE, page + "")
                .addParams(PARAM_URL_SIZE, PARAMS_PAGE_SIZE)
                .addParams("category", "1")
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                Status_Products status_products = GsonUtil.fromJson(response, Status_Products.class);
                if (CONNECTION_STATUS_SUCCESS.equals(status_products.getStatus_code())) {
                    isEnd = status_products.getData().is_end();
                    if (page == 1)
                        mCommodityListAdapter.setNewData(status_products.getData().getList());
                    else {
                        mCommodityListAdapter.addData(status_products.getData().getList());
                        mCommodityListAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }


    @Override
    public void onRefresh() {
        mCommodityListAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                mCommodityListAdapter.getData().clear();
                initData();
                mCommodityListAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    mCommodityListAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        initData();
                    } else {
                        isErr = true;
                        Toast.makeText(mContext, R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        mCommodityListAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }


    @Override
    public void onItemClick(int position) {

    }


    @Override
    public void onResume() {
        super.onResume();
        mConvenientBanner.startTurning(3000);
    }

    @Override
    public void onPause() {
        super.onPause();
        mConvenientBanner.stopTurning();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void showHead() {
        mUserEntity = SPUtil.getUser();
//        CommonUtils.loadImageView(getActivity(), mUserEntity.getData().getCover(), R.mipmap.default_head, iv_user_head);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_USER_HEAD_UPDATE:
                showHead();
                break;
        }
    }
}
